package xyz.xiangyushui.util.dataBase;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class CommonDao<T> {
	private DBUtil db;
	private String tableName;

	/**
	 * 
	 * @param t
	 * @param except
	 */
	public void save(T t, String[] except) {
		String table = tableName == null ? getTableName(t) : tableName;
		Map<String, Object> m=getKeyValues(t, except);
		StringBuilder keys=new StringBuilder();
		List<Object> values=new LinkedList<>();
		m.forEach((k,v)->{
			keys.append(k+",");
			values.add(v);
		});
		String fields=keys.toString();
		db.executeUpdate("insert into "+table+"("+fields.substring(0, fields.length()-1)+")"+" values("+makeQuestionMark(values.size())+")", values.toArray(new Object[values.size()]));

	}

	public void save(T t) {
		save(t,null);
	}
	
	

	/**
	 * 
	 * @param m
	 * @return
	 */
	public List<T> get(Map<String, Object> m) {

		return null;
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

	
	private String makeQuestionMark(int n){
		StringBuilder sb=new StringBuilder();
		for(int i=0;i<n-1;i++){
			sb.append("?,");
		}
		return sb.append("?").toString();
	}
	
	
	

	private String getTableName(T t) {
		String fullName=t.getClass().getName();
		return fullName.substring(fullName.lastIndexOf('.')+1).toLowerCase();
	}

	private Map<String, Object> getKeyValues(T t, String[] except) {
		Map<String, Object> map = new HashMap<>();
		Field[] fs = t.getClass().getDeclaredFields();
		for (int i = 0; i < fs.length; i++) {
			Field f = fs[i];
			f.setAccessible(true);
			if (contains(except, f.getName())) {
				Object val = null;
				try {
					val = f.get(t);
				} catch (IllegalArgumentException | IllegalAccessException e) {
					e.printStackTrace();
				}
				map.put(f.getName(), val);
			}
		}
		return map;
	}


	private boolean contains(String[] array, String target) {
		if(array==null) return true;
		boolean contains = false;
		for (String s : array) {
			if (s.equals(target)) {
				contains = true;
				break;
			}
		}
		return contains;
	}
}
